import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import context from '../../context'
import './Item.css'
export default class Item extends Component {
  state = {
    tN: '',
  }
  static contextType = context
  render() {
    const {
      todo: { todoName, id, isDone },
    } = this.props

    const { tN } = this.state

    const editId = this.context
    return (
      <li>
        {editId !== id ? (
          <label>
            <input type="checkbox" checked={isDone} onChange={() => {}} />
            <span className={isDone ? 'done' : ''}>{todoName}</span>
          </label>
        ) : (
          <input
            type="text"
            value={tN}
            onChange={(e) => {
              this.setState({
                tN: e.target.value.trim(),
              })
            }}
            onKeyUp={(e) => {
              if (!tN || e.key !== 'Enter') return
              PubSub.publish('setTodoName', { id, tN })
            }}
          />
        )}
        <button className="btn btn-danger">删除</button>
        <button
          className="btn btn-edit"
          onClick={() => {
            this.setState({
              tN: todoName,
            })
            PubSub.publish('setEditId', editId !== id ? id : undefined)
          }}
        >
          {editId !== id ? '编辑' : '取消'}
        </button>
      </li>
    )
  }
}
